﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Linq;
using System.Web;

namespace Argument.Setup
{
    public class RevisionRunner
    {

        public static int RunRevisions(SqlConnection conn)
        {



            string dir = HttpContext.Current.Server.MapPath("~/App_Data/Revisions");
            XDocument revDoc = XDocument.Load(Path.Combine(dir, "RevisionList.xml"));

            dir = Path.Combine(dir, "SQLScripts");

            int maxRev = RunBootstrap(dir, conn);


            int count = 0;

            foreach (XElement node in revDoc.Descendants("Revision"))
            {
                int sequence = int.Parse(node.Attribute("sequence").Value);

                if (sequence <= maxRev)
                {
                    continue;
                }

                string filename = node.Attribute("filename").Value;
                string path = Path.Combine(dir, filename);

                ExecuteSQL(path, conn);

                UpdateMaxRevision(sequence, conn);

                count++;
            }

            //foreach (string script in list) {
            //    int result = ExecuteSQL(script, conn);
            //    if (result != 0)
            //    {
            //        throw new Exception(String.Format("Result of running script {0} was not 0.", script));
            //    }
            //}

            return count;
        }

        private static void UpdateMaxRevision(int sequence, SqlConnection conn)
        {
            using (SqlCommand cmd = new SqlCommand("USP_SetMaxRevision", conn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@max", sequence);
                cmd.ExecuteNonQuery();
            }
        }

        private static int RunBootstrap(string dir, SqlConnection conn)
        {
            using (SqlCommand cmd = GetCommand(Path.Combine(dir, "Bootstrap.sql"), conn)) {
                return (int) cmd.ExecuteScalar();
            }
        }


        private static SqlCommand GetCommand(string filename, SqlConnection conn)
        {
            var content = File.ReadAllText(filename);
            return new SqlCommand(content, conn);
        }

        private static int ExecuteSQL(string filename, SqlConnection conn)
        {
            using (SqlCommand cmd = GetCommand(filename, conn)) {
                return cmd.ExecuteNonQuery();
            }
        }

    }
}
